// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("Spud 2 (fixed)", overlay=false, max_bars_back=1000)

// Inputs
Per = input.int(15, minval=5, title="Period (must be multiple of 5)")
Pk = input.int(5, title="Pk")
Pd = input.int(3, title="Pd")
Ps = input.int(3, title="Ps")

factor = Per / 5

// Custom Stochastic Calculation on current bar using past bars only
customStoch() =>
    sumlo = 0.0
    sumhi = 0.0
    for j = 0 to Ps - 1
        barsBack = j * (Per / timeframe.multiplier)
        if barsBack <= bar_index
            clos1 = close[barsBack]
            pkLength = int(Pk * factor)
            highestHigh = ta.highest(high, pkLength)[barsBack]
            lowestLow = ta.lowest(low, pkLength)[barsBack]
            sumlo += clos1 - lowestLow
            sumhi += highestHigh - lowestLow
    sumhi <= 0 ? 100 : (sumlo / sumhi) * 100

// Linear regression on series data
lreg_series(buffer, length) =>
    if length <= 1
        na
    else
        Sx = 0.0
        Sy = 0.0
        Sxx = 0.0
        Sxy = 0.0
        for i = 0 to length - 1
            x = i * 1.0
            y = buffer[i]
            Sx += x
            Sy += y
            Sxx += x * x
            Sxy += x * y
        n = length * 1.0
        c = Sxx * n - Sx * Sx
        if c == 0
            na
        else
            beta = (n * Sxy - Sx * Sy) / c
            alpha = (Sy - beta * Sx) / n
            alpha

// Calculate SBuffer for current bar
SBuffer = customStoch()

// Calculate MaBuffer as linear regression of SBuffer over last Pd bars
MaBuffer = bar_index >= Pd - 1 ? lreg_series(SBuffer, Pd) : na

// Plot
//plot(SBuffer, color=color.gray, title="Stoch")
plot(MaBuffer, color=color.red, title="Ma")

